package bom.example.common.session.impl;

import bom.example.common.session.SessionProvider;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * @author X.I.O
 * @title: HttpSessionProvider
 * @projectName demo
 * @description: TODO
 * @date 2021/11/12 11:15
 */
@Component
public class HttpSessionProvider implements SessionProvider {

    @Override
    public Serializable getAttribute(HttpServletRequest request, String name) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            return (Serializable) session.getAttribute(name);
        } else {
            return null;
        }
    }

    @Override
    public void setAttribute(HttpServletRequest request,
                             String name, Serializable value) {
        HttpSession session = request.getSession();
        session.setAttribute(name, value);
    }

    @Override
    public String getSessionId(HttpServletRequest request) {
        if(request==null){
            return "";
        }
        return request.getSession().getId();
    }


    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }

    @Override
    public void removeAttribute(HttpServletRequest request, String id) {
        request.getSession().removeAttribute(id);
    }
}
